<template>
  <div class="pagination">
    <button :disabled="pageNo === 1" @click="$emit('changePages', pageNo - 1)">
      上一页
    </button>
    <button
      v-show="startEndPage.start > 1"
      :class="{ active: pageNo === 1 }"
      @click="$emit('changePages', 1)"
    >
      1
    </button>

    <button v-show="startEndPage.start > 2">···</button>

    <button
      v-for="(item, index) in startEndPage.end - startEndPage.start + 1"
      :key="index"
      :class="{ active: pageNo === index + startEndPage.start }"
      @click="$emit('changePages', index + startEndPage.start)"
    >
      {{ index + startEndPage.start }}
    </button>

    <button v-show="startEndPage.end < totalPages - 1">···</button>
    <button
      v-show="startEndPage.end < totalPages"
      :class="{ active: pageNo === totalPages }"
      @click="$emit('changePages', totalPages)"
    >
      {{ totalPages }}
    </button>
    <button
      :disabled="pageNo === totalPages"
      @click="$emit('changePages', pageNo + 1)"
    >
      下一页
    </button>

    <button style="margin-left: 30px">共{{ total }}条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["totalPages", "pageNo", "continuePage", "total"],
  computed: {
    startEndPage() {
      //解构出来"totalPages","pageNo","continuePage"
      const { totalPages, pageNo, continuePage } = this;
      //根据当前页计算连续页
      let start = 0,
        end = 0;
      //判断连续页大于总页数
      if (continuePage > totalPages) {
        //如果总页数小于连续页,起始是1和结束是总页数
        (start = 1), (end = totalPages);
      } else {
        //如果总页数大于连续页
        //首先根据当前的页码,计算出连续页的开头 和 连续页的结尾
        start = pageNo - Math.floor(continuePage / 2);
        end = pageNo + Math.floor(continuePage / 2);
      }

      if (start < 1) {
        //如果start小于1  则直接设置起始为1
        (start = 1),
          //如果start已经变成1了 则直接设置end为连续页长度
          (end = continuePage);
      }
      if (end > totalPages) {
        start = totalPages - continuePage + 1;
        end = totalPages;
      }

      return { start, end };
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
